package com.google.project.client.HumanResources;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.client.Service.SpecializeService;
import com.google.project.client.Service.SpecializeServiceAsync;
import com.google.project.client.Service.UsersService;
import com.google.project.client.Service.UsersServiceAsync;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.SpecializeDTO;
import com.google.project.shared.UsersDTO;

public class HMStaffList extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField Button createEmployeeBtn;
	@UiField(provided = true) CellTable<UsersDTO> ctbUserList = new CellTable<UsersDTO>();
	@UiField ListBox cbSpecialize;
	@UiField ListBox cbExperient;
	@UiField ListBox cbStatus;
	@UiField ListBox cbProject;
	@UiField TextBox txtEmployeeName;
	@UiField Button btnSearch;
	@UiField Button btnDelete;
	@UiField SimplePager pager;

	interface Binder extends UiBinder<Widget, HMStaffList> {
	}

	private final MultiSelectionModel<UsersDTO> selectionModel = new MultiSelectionModel<UsersDTO>();
	private final UsersServiceAsync userService = GWT.create(UsersService.class);
	private final ProjectServiceAsync projectService = GWT.create(ProjectService.class);
	private final SpecializeServiceAsync specService = GWT.create(SpecializeService.class);
	private List<ProjectDTO> projectDTOList = new ArrayList<ProjectDTO>();
	private List<UsersDTO> userDTOList = new ArrayList<UsersDTO>();
	private List<UsersDTO> userList = new ArrayList<UsersDTO>();
	private String status;

	public HMStaffList() {
		initWidget(binder.createAndBindUi(this));
		initCbSpecialize();
		initCbExperient();
		initCbStatus();
		initCbProject();
		bindData();
	}

	public HMStaffList(int _status) {
		this.status = _status + "";
		initWidget(binder.createAndBindUi(this));
		initCbSpecialize();
		initCbExperient();
		initCbStatus();
		initCbProject();
		searchFunction(status.trim());
	}

	public void initCbProject() {
		projectService.getProjectList(new AsyncCallback<List<ProjectDTO>>() {
			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(List<ProjectDTO> result) {
				cbProject.addItem("---Tất cả---", "0");
				for (ProjectDTO projectDTO : result) {
					projectDTOList.add(projectDTO);
					cbProject.addItem(projectDTO.getProjectName(), projectDTO.getProjectID());
				}
			}
		});
		cbProject.setSelectedIndex(0);
	}

	public void initCbStatus() {
		cbStatus.addItem("---Tất cả---", "-1");
		cbStatus.addItem("Chưa tham gia", "0");
		cbStatus.addItem("Đang tham gia", "1");
		cbStatus.setSelectedIndex(-1);
	}

	public void initCbExperient() {
		cbExperient.addItem("---Tất cả---", "0");
		cbExperient.addItem("< 1 năm", "1");
		cbExperient.addItem("1-3 năm", "2");
		cbExperient.addItem("3-5 năm", "3");
		cbExperient.addItem("5-10 năm", "4");
		cbExperient.addItem("> 10 năm", "5");
		cbExperient.setSelectedIndex(0);
	}

	public void initCbSpecialize() {
		specService.getSpecList(new AsyncCallback<List<SpecializeDTO>>() {
			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(List<SpecializeDTO> result) {
				cbSpecialize.addItem("---Tất cả---", "0");
				for (SpecializeDTO specializeDTO : result) {
					cbSpecialize.addItem(specializeDTO.getSpecializeName(), specializeDTO.getId());
				}
			}
		});
		cbSpecialize.setSelectedIndex(0);
	}

	public void bindData() {
		userService.getUserList(new AsyncCallback<List<UsersDTO>>() {
			@Override
			public void onSuccess(List<UsersDTO> result) {
				userDTOList = result;
				loadData(result);
				initTable();
			}

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Có lỗi trong quá trình tải thông tin!");
			}
		});
	}

	//Fill data to celltable
	protected void loadData(List<UsersDTO> userList) {

		ListDataProvider<UsersDTO> dataProvider = new ListDataProvider<UsersDTO>();

		//Add the data to the data provider, which automatically pushes it to
		//the widget
		List<UsersDTO> list = dataProvider.getList();
		for(int i = 0; i < userList.size(); i++) {
			userList.get(i).setIndex(i+1);
			list.add(userList.get(i));
		}
		pager.setDisplay(ctbUserList);
		//Connect the table to the data provider.
		dataProvider.addDataDisplay(ctbUserList);
	}
	
	public void initTable() {
		//STT
		TextColumn<UsersDTO> indexColumn = new TextColumn<UsersDTO>() {
			@Override
			public String getValue(UsersDTO user) {
				return user.getIndex()+"";
			}
		};
		//Check box
		ctbUserList.setSelectionModel(selectionModel, DefaultSelectionEventManager.<UsersDTO> createCheckboxManager());
		Column<UsersDTO, Boolean> checkColumn = new Column<UsersDTO, Boolean>(new CheckboxCell(true, false)) {
			@Override
			public Boolean getValue(UsersDTO user) {
				//Get the value from the selection model.
				return selectionModel.isSelected(user);
			}
		};

		//Ma nhan vien
		Column<UsersDTO, String> userCodeColumn = new Column<UsersDTO, String>(new ClickableTextCell()) {
			@Override
			public String getValue(UsersDTO user) {
				return user.getUserCode();
			}
		};
		userCodeColumn.setFieldUpdater(new FieldUpdater<UsersDTO, String>() {

			@Override
			public void update(int index, UsersDTO user, String value) {
				HMEntrypoint.get().HMCreateEmp(user.getUserId());
			}

		});


		// Ten nhan vien userNameColumn
		TextColumn<UsersDTO> userNameColumn = new TextColumn<UsersDTO>() {
			@Override
			public String getValue(UsersDTO user) {
				return user.getFullName();
			}
		};
		
		//Chuyen mon
		TextColumn<UsersDTO> specializeColumn = new TextColumn<UsersDTO>() {
			@Override
			public String getValue(UsersDTO user) {
				return user.getSpecializeName();
			}
		};
		//Kinh nghiem
		TextColumn<UsersDTO> experientColumn = new TextColumn<UsersDTO>() {
			@Override
			public String getValue(UsersDTO user) {
				int exp = user.getExperient();
				String result = "";
				if (exp == 1) {
					result += " < 1 năm";
				} else if (exp == 2) {
					result += "1-3 năm";
				} else if (exp == 3) {
					result += "3-5 năm";
				} else if (exp == 4) {
					result += "5-10 năm";
				} else if (exp == 5) {
					result += " > 10 năm";
				}
				return result;
			}
		};
		//Tuoi
		TextColumn<UsersDTO> ageColumn = new TextColumn<UsersDTO>() {
			@SuppressWarnings("deprecation")
			@Override
			public String getValue(UsersDTO user) {
				Date todayD = new Date(System.currentTimeMillis());
				Date birthDay = new Date(user.getBirthday());
				int age = todayD.getYear() - birthDay.getYear();
				return age + "";
			}
		};
		//Du an
		TextColumn<UsersDTO> projectColumn = new TextColumn<UsersDTO>() {
			@Override
			public String getValue(UsersDTO user) {
				String result = "";
				if (Integer.parseInt(user.getStatus()) != 0 && user.getCurrentProjID() != null) {
					for (ProjectDTO project : projectDTOList) {
						if (user.getCurrentProjID().equals(project.getProjectID())) {
							result += project.getProjectName();
							break;
						}
					}
				}
				return (result);
			}
		};
		//Tinh trang
		TextColumn<UsersDTO> statusColumn = new TextColumn<UsersDTO>() {
			@Override
			public String getValue(UsersDTO user) {
				String _status = ""; 
				if (user.getCurrentProjID() != null) {
					_status += "Đang tham gia";
				} else {
					_status += "Chưa tham gia";
				}
				return _status;
			}
		};

		//Thiet lap cac thong so cho bang
		ctbUserList.setWidth("100%", true);
		ctbUserList.setPageSize(5);
		ctbUserList.setPageStart(0);
		ctbUserList.setStyleName("ttable");

		//Add cac cot cho bang
		ctbUserList.addColumn(indexColumn, "STT");
		ctbUserList.setColumnWidth(indexColumn, 40, Unit.PX);
		
		ctbUserList.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant(""));
		ctbUserList.setColumnWidth(checkColumn, 40, Unit.PX);
		
		ctbUserList.addColumn(userCodeColumn, "Mã nhân viên");
		userCodeColumn.setCellStyleNames("celltable");
		ctbUserList.setColumnWidth(userCodeColumn, 120, Unit.PX);
		ctbUserList.getColumn(ctbUserList.getColumnIndex(userCodeColumn)).setHorizontalAlignment(HasAlignment.ALIGN_LEFT);
		
		ctbUserList.addColumn(userNameColumn, "Tên nhân viên");
		ctbUserList.setColumnWidth(userNameColumn, 20.0, Unit.PCT);
		ctbUserList.getColumn(ctbUserList.getColumnIndex(userNameColumn)).setHorizontalAlignment(HasAlignment.ALIGN_LEFT);
		
		ctbUserList.addColumn(specializeColumn, "Chuyên môn");
		ctbUserList.setColumnWidth(specializeColumn, 15.0, Unit.PCT);
		ctbUserList.getColumn(ctbUserList.getColumnIndex(specializeColumn)).setHorizontalAlignment(HasAlignment.ALIGN_LEFT);
		
		ctbUserList.addColumn(ageColumn, "Tuổi");
		ctbUserList.setColumnWidth(ageColumn, 10.0, Unit.PCT);
		ctbUserList.getColumn(ctbUserList.getColumnIndex(ageColumn)).setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
		
		ctbUserList.addColumn(experientColumn, "Kinh nghiệm");
		ctbUserList.setColumnWidth(experientColumn, 15.0, Unit.PCT);
		ctbUserList.getColumn(ctbUserList.getColumnIndex(experientColumn)).setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
		
		ctbUserList.addColumn(projectColumn, "Dự án");
		ctbUserList.setColumnWidth(projectColumn, 12.5, Unit.PCT);
		ctbUserList.getColumn(ctbUserList.getColumnIndex(projectColumn)).setHorizontalAlignment(HasAlignment.ALIGN_LEFT);
		
		ctbUserList.addColumn(statusColumn, "Trạng thái");
		ctbUserList.setColumnWidth(statusColumn, 12.5, Unit.PCT);
		ctbUserList.getColumn(ctbUserList.getColumnIndex(statusColumn)).setHorizontalAlignment(HasAlignment.ALIGN_LEFT);
	}

	@UiHandler("createEmployeeBtn")
	void onCreateEmployeeBtnClick(ClickEvent event) {
		HMEntrypoint.get().HMCreateEmp();
	}

	@UiHandler("btnSearch")
	void onBtnSearchClick(ClickEvent event) {
		searchFunction();
	}

	//Ham search
	private void searchFunction() {
		String employeeName = txtEmployeeName.getText().trim();
		String projectId = cbProject.getValue(cbProject.getSelectedIndex());
		String specializeId = cbSpecialize.getValue(cbSpecialize.getSelectedIndex());
		int status = -2;
		if(cbStatus.getValue(cbStatus.getSelectedIndex()) != null) {
			status = Integer.parseInt(cbStatus.getValue(cbStatus.getSelectedIndex()));
		}
		int experient = -2;
		if(cbExperient.getValue(cbExperient.getSelectedIndex()) != null) {
			experient = Integer.parseInt(cbExperient.getValue(cbExperient.getSelectedIndex()));
		}
		Boolean condition = true;
		List<UsersDTO> temple = new ArrayList<UsersDTO>();
		
		for(UsersDTO user : userDTOList) {
			
			if(employeeName != null) {
				condition = condition && (user.getFullName().contains(employeeName));
			}
			if(user.getCurrentProjID() == null) {
				user.setCurrentProjID("0");
			}
			if((cbProject.getValue(cbProject.getSelectedIndex()) != null) && (!cbProject.getValue(cbProject.getSelectedIndex()).equalsIgnoreCase("0"))) {
				condition = condition && (user.getCurrentProjID().equals(projectId));
			}
			if((cbSpecialize.getValue(cbSpecialize.getSelectedIndex()) != null) && (!cbSpecialize.getValue(cbSpecialize.getSelectedIndex()).equalsIgnoreCase("0"))) {
				condition = condition && (user.getSpecializeID().equals(specializeId));
			}
			if((cbStatus.getValue(cbStatus.getSelectedIndex()) != null) && (!cbStatus.getValue(cbStatus.getSelectedIndex()).equalsIgnoreCase("-1"))) {
				int check = 0;
				if(user.getCurrentProjID() != null) {
					check = 1;
				}
				condition = condition && (check == status);
			}
			if((cbExperient.getValue(cbExperient.getSelectedIndex()) != null) && (!cbExperient.getValue(cbExperient.getSelectedIndex()).equalsIgnoreCase("0"))) {
				condition = condition && (user.getExperient() == experient);
			}
			if(condition) {
				temple.add(user);
			}
			condition = true;
		}
		if(temple != null) {
			loadData(temple);
		} else {
			Window.alert("Không tìm thấy dữ liệu");
			loadData(temple);
		}
	}
	
	//Tim kiem nhung nhan vien chua co tai khoan
	public void searchFunction(final String _status) {
		userService.getUserList(new AsyncCallback<List<UsersDTO>>() {
			@Override
			public void onSuccess(List<UsersDTO> result) {
				userDTOList = result;
				for(UsersDTO userDTO : result) {
					if(userDTO.getStatus().equals(_status)) {
						userList.add(userDTO);
					}
				}
				loadData(userList);
				initTable();
			}

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Có lỗi trong quá trình tải thông tin!");
			}
		});
	}

	@UiHandler("btnDelete")
	void onBtnDeleteClick(ClickEvent event) {
		Set<UsersDTO> listChecked = selectionModel.getSelectedSet();
		if(listChecked.size() == 0) {
			Window.alert("Bạn chưa chọn để xóa!");
		} else {
			List<UsersDTO> list = new ArrayList<UsersDTO>();
			for (UsersDTO user : listChecked) {
				list.add(user);
			}
			if (Window.confirm("Bạn có chắc chắn muốn xóa?")) {
				userService.deleteUserList(list, new AsyncCallback<Void>() {
	
					@Override
					public void onFailure(Throwable caught) {
						Window.alert("Có lỗi trong quá trình xóa!");
					}
	
					@Override
					public void onSuccess(Void result) {
						HMEntrypoint.get().clearMainPanel();
						HMEntrypoint.get().HMStaffList();
					}
				});
			}
		}
	}
}
